#pragma once 

#include<iostream>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<sys/wait.h>


#include<string>
#include<cstring>
using namespace std;    

#include"Log.hpp"
extern Log lg;
const int backlog = 10;

enum
{
    SocketErr = 2,
    BindErr,
    ListenErr,

};


class Socket
{
public:
    Socket()
    {}
    ~Socket()
    {}
public:
    void InitSocket()
    {
        //创建流式套接字:
        sockfd_ = socket (AF_INET, SOCK_STREAM, 0);
        if (sockfd_ < 0)
        {
            lg(Fatal, "socket error, %s %d", strerror(errno), errno);   
            exit(SocketErr);
        }        
    }
    void Bind(uint16_t port)
    {
        //先创建addr结构体对象， 再将结构体对象清空:
        struct sockaddr_in  local;
        memset(&local, 0, sizeof(local));

        //然后对addr结构体对象进行初始化:
        local.sin_family = AF_INET;
        local.sin_port = htons(port);  //htons主机序列转网络序列
        local.sin_addr.s_addr = INADDR_ANY;

        if (bind(sockfd_, (const sockaddr*)&local, sizeof(local)) < 0)
        {
            lg(Fatal, "bind error, %s %d", strerror(errno), errno);   
            exit(BindErr);
        }
    }
    void Listen()
    {
        if (listen(sockfd_, backlog) < 0)
        {
            lg(Fatal, "listen error, %s %d", strerror(errno), errno);   
            exit(ListenErr);
        }
    }
    int Accept(string * clientip, uint16_t* clientport)
    {
        //知道文件描述符是谁， 也要知道是谁连接的我:

        struct sockaddr_in peer; //获取远端信息；
        socklen_t len = sizeof(peer);
        int newfd = accept(sockfd_, (sockaddr*)&peer, &len); 

        //
        if (newfd < 0)
        {
            lg(Waring, "accept error, %s %d", strerror(errno), errno);   

            return -1;
        }
        char ipstr[64];
        //inet_ntop是将网络序列转化为字符串风格。
        inet_ntop(AF_INET, &peer.sin_addr, ipstr, sizeof(ipstr));
        *clientip = ipstr; 
        *clientport = ntohs(peer.sin_port); //ntoh是网络序列转成主机序列。 

        return newfd;
    }
    void Close()
    {
        close(sockfd_);
    }

    bool Connect(const string &ip, const uint16_t &port)
    {
        struct sockaddr_in peer;
        memset(&peer, 0, sizeof(peer));   
        peer.sin_family = AF_INET;
        peer.sin_port = htons(port);  //主机序列转网络序列
        inet_pton(AF_INET, ip.c_str(), &(peer.sin_addr));   //字符串转网络序列

        int n = connect(sockfd_, (sockaddr*)&peer, sizeof(peer));
        if (n == -1) 
        {
            cerr << "connect to " << ip << ": " << port << endl;
            return false;
        }

        return true; 
    }

private:
    int sockfd_;
};